package cn.com.hatech.blog.module.admin.attach.controller;

import cn.com.hatech.blog.common.controller.BaseController;
import cn.com.hatech.blog.common.exception.TipException;
import cn.com.hatech.blog.common.result.RestResponse;
import cn.com.hatech.blog.common.utils.TaleUtils;
import cn.com.hatech.blog.module.admin.attach.service.IAttachService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @projectName: hatech-blog
 * @package: cn.com.hatech.blog.module.admin.controller
 * @className: AttachController
 * @author: xuruikai
 * @description: 附件管理控制器
 * @date: 2020/1/11 14:27
 * @version: 1.0
 */
@RestController
@RequestMapping("api/v1/admin/attach")
@Slf4j
public class AttachRestController extends BaseController {

    public static final String CLASSPATH = TaleUtils.getUploadFilePath();

    @Resource
    private IAttachService attachService;

    /**
     * 上传文件接口
     *
     * @return
     */
    @PostMapping(value = "/upload")
    @ResponseBody
    @Transactional(rollbackFor = TipException.class)
    public RestResponse upload(@RequestParam("file") MultipartFile[] multipartFiles) {
        List<String> errorFiles = this.attachService.uploadFile(multipartFiles);
        if (errorFiles.isEmpty()) {
            return RestResponse.ok();
        }
        return RestResponse.fail(StringUtils.join(errorFiles, ","));
    }

    /**
     * 删除附件
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public RestResponse delete(@RequestParam String id) {
        int num = attachService.deleteById(id);
        if (num > 0) {
            return RestResponse.ok();
        }
        return RestResponse.fail();
    }

}
